<?php

namespace common\components\helpers;

use common\models\datas\Attribute;
use common\models\datas\AttributeValue;
use common\models\datas\Customer;
use common\models\datas\CustomerRegisterRelation;
use common\models\datas\Regions;
use common\models\datas\Setting;
use common\models\datas\Site;
use frontend\models\datas\Goods;
use frontend\models\datas\GoodsAttr;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\rest\ViewAction;

/**
 * 扩展系统功能助手类
 * @author: 郭建飞
 * Date: 2015-3-11
 * Time: 11:11
 */
class Fun
{

    /**
     * 自动添加site参数的url助手方法
     * @param array $url 输入的的地址参数。
     * @param bool $scheme
     * @return string
     */
    public static function url($url = '', $scheme = false)
    {
        $url = (array)$url;
        $route = \Yii::$app->request->get('site') != null ? ArrayHelper::merge($url, ['site' => \Yii::$app->request->get('site')]) : $url;
        if ($scheme) {
            return \Yii::$app->getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null);
        } else {
            return \Yii::$app->getUrlManager()->createUrl($route);
        }

    }

    /**
     * 自动添加site参数的cache取得助手方法
     * @param string $cache_name 缓存存储用的key
     * @param bool $site 如若在总后台调用此方法不需要传递$site参数，如若在分店后台需要调用全局缓存再要传递$site=false，调用分店缓存不需要传递此参数
     * @return array
     */
    public static function cache($cache_name, $site = true)
    {
        \Yii::$app->cacheManage->site = '';
        \Yii::$app->cacheManage->cacheName = '';
        \Yii::$app->cacheManage->fieldName = '';
        if (!is_string($cache_name)) return false;
        $cache_info = explode('_', $cache_name);
        if (count($cache_info) == 3) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
            \Yii::$app->cacheManage->fieldName = $cache_info[1];
        } elseif (count($cache_info) == 2) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
            \Yii::$app->cacheManage->fieldName = '';
        } else {
            return false;
        }

        if ($site && isset(\Yii::$app->request->get()['site'])){
            \Yii::$app->cacheManage->site = \Yii::$app->request->get('site');
        }
        if (isset(\Yii::$app->controller->module) && \Yii::$app->controller->module->id == 'app-wechat') {
            $site_id=Fun::getSiteId();
            if($site_id){
                $site_obj=Site::findOne($site_id);
                if($site_obj!=null){
                    \Yii::$app->cacheManage->site = $site_obj->domain;
                }
            }
        }
        return \Yii::$app->cacheManage->findCache();
    }

    /**
     * 自动添加site参数额更新cache助手
     * @param string $cache_name 缓存存储用的key
     * @param bool $site 如若在总后台调用此方法不需要传递$site参数，如若在分店后台需要调用全局缓存再要传递$site=false，调用分店缓存不需要传递此参数
     * @return array
     */
    public static function updateCache($cache_name, $site = true)
    {
        if (!is_string($cache_name)) return false;
        $cache_info = explode('_', $cache_name);
        if (count($cache_info) == 3) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
            \Yii::$app->cacheManage->fieldName = $cache_info[1];
        } elseif (count($cache_info) == 2) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
        } else {
            return false;
        }
        if ($site && \Yii::$app->request->get('site') != null) \Yii::$app->cacheManage->site = \Yii::$app->request->get('site');
        if (isset(\Yii::$app->controller->module) && \Yii::$app->controller->module->id == 'app-wechat') {
            $site_id=Fun::getSiteId();
            if($site_id){
                $site_obj=Site::findOne($site_id);
                if($site_obj!=null){
                    \Yii::$app->cacheManage->site = $site_obj->domain;
                }
            }
        }

        return \Yii::$app->cacheManage->updateCache();
    }
    /*
         * 微信自定义菜单
         */
    public static function wechatCache($cache_name,$wechat_id = 0){
        if(empty($wechat_id)){
            return false;
        }
        \Yii::$app->cacheManage->wechatId = $wechat_id;
        \Yii::$app->cacheManage->cacheName = '';
        \Yii::$app->cacheManage->fieldName = '';
        if (!is_string($cache_name)) return false;
        $cache_info = explode('_', $cache_name);
        if (count($cache_info) == 3) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
            \Yii::$app->cacheManage->fieldName = $cache_info[1];
        } elseif (count($cache_info) == 2) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
            \Yii::$app->cacheManage->fieldName = '';
        } else {
            return false;
        }
        return \Yii::$app->cacheManage->findCache();
    }

    /*
     * 更新微信缓存
     */
    public static function updateWechatCache($cache_name,$wechatId=0)
    {
        if (!is_string($cache_name)) return false;
        $cache_info = explode('_', $cache_name);
        if (count($cache_info) == 3) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
            \Yii::$app->cacheManage->fieldName = $cache_info[1];
        } elseif (count($cache_info) == 2) {
            \Yii::$app->cacheManage->cacheName = $cache_info[0];
        } else {
            return false;
        }
        \Yii::$app->cacheManage->wechatId = $wechatId;

        return \Yii::$app->cacheManage->updateCache();
    }
    /**
     * 检查站点是否开通
     * @param object $event 事件
     */
    public static function checkSite($event)
    {
        if (\Yii::$app->controller->module->id == 'app-frontend') {
            $site = \Yii::$app->request->get('site');
            $site_cache = self::cache('site_cache', false);
            //var_dump($site_cache[$site]);die;
            if (!isset($site_cache[$site])) $event->isValid = false;
            if (!isset($site_cache[$site]['db'])) $event->isValid = false;
        }
    }

    /**
     * 获取分店系统的数据库连接信息
     */
    public static function getSiteDb()
    {
        $site = null;
        if(method_exists(\Yii::$app->request,'get')){
            $site = \Yii::$app->request->get('site');
        }
        /*bug #163 缓存中获取数据库配置有问题*/
        $site_cache = self::cache('site_cache', false);
        if(!empty($site_cache)){
            foreach($site_cache as $sc){//如果有db的配置是空的则清除缓存并重新获取
                if(!empty($sc)){
                    if(isset($sc['db']) && !empty($sc['db'])){
                        if(isset($sc['db']['dsn']) && !empty($sc['db']['dsn'])){
                            continue;
                        }else{
                            self::updateCache('site_cache',false);
                            $site_cache = self::cache('site_cache', false);
                            break;
                        }
                    }else{
                        self::updateCache('site_cache',false);
                        $site_cache = self::cache('site_cache', false);
                        break;
                    }
                }else{
                    self::updateCache('site_cache',false);
                    $site_cache = self::cache('site_cache', false);
                    break;
                }
            }
        }else{
            self::updateCache('site_cache',false);
            $site_cache = self::cache('site_cache', false);
        }
        if($site == null){//当获取不到site的之后，是微信端的获取，直接从cookie中获取siteid
            $site_id = Fun::getSiteId();
            foreach ($site_cache as $k => $v) {
                if ($site_id == $v['id']) {
                    $site = $v['domain'];
                }
            }

//            else{//测试回调
//                $site_id = 2;
//                foreach ($site_cache as $k => $v) {
//                    if ($site_id == $v['id']) {
//                        $site = $v['domain'];
//                    }
//                }
//            }
        }
        if ($site == null){
            return false;
        }
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        return \Yii::createObject($site_cache[$site]['db']);
    }


    public static function getSysDb()
    {
        return \Yii::createObject(\Yii::$app->params['sys_back_db']);
    }

    /**
     * 获取分店系统和web的数据库连接信息
     * @param $site_id (当$site_id==null表示获取web数据库连接，$site_id!=null表示获取相应分店数据库信息)
     */
    public static function getSiteDatabases($site_id = '')
    {
        $site = '';
        if ($site_id != null) {
            $site_cache = Fun::cache('site_cache');
            foreach ($site_cache as $k => $v) {
                if ($site_id == $v['id']) {
                    $site = $v['domain'];
                }
            }
            if ($site == null) return false;
            if (!isset($site_cache[$site])) return false;
            if (!isset($site_cache[$site]['db'])) return false;
            return \Yii::createObject($site_cache[$site]['db']);
        } else {
            return \Yii::createObject(\Yii::$app->params['web_db']);
        }
    }

    /**
     * 设置系统和分店系统的数据库连接信息（该方法可获取lastInsertId）
     * @param $site_id (当$site_id==null表示设置系统数据库连接，$site_id!=null表示设置相应分店数据库信息)
     */
    public static function setSiteDatabases($site_id = '')
    {
        /*if ($site_id != null) {
            $site = '';
            $site_cache = Fun::cache('site_cache');
            foreach ($site_cache as $k => $v) {
                if ($site_id == $v['id']) {
                    $site = $v['domain'];
                }
            }
            if ($site == null) return false;
            if (!isset($site_cache[$site])) return false;
            if (!isset($site_cache[$site]['db'])) return false;
            \Yii::$app->set('db', $site_cache[$site]['db']);
        } else {
            \Yii::$app->set('db', \Yii::$app->params['sys_back_db']);
        }
        $site = \Yii::$app->request->get('site');
        $site_cache = self::cache('site_cache', false);*/
        /*bug #163 缓存中获取数据库配置有问题*/
        $site = \Yii::$app->request->get('site');
        $site_cache = self::cache('site_cache', false);
        if(!empty($site_cache)){
            foreach($site_cache as $sc){//如果有db的配置是空的则清除缓存并重新获取
                if(!empty($sc)){
                    if(isset($sc['db']) && !empty($sc['db'])){
                        if(isset($sc['db']['dsn']) && !empty($sc['db']['dsn'])){
                            continue;
                        }else{
                            self::updateCache('site_cache',false);
                            $site_cache = self::cache('site_cache', false);
                            break;
                        }
                    }else{
                        self::updateCache('site_cache',false);
                        $site_cache = self::cache('site_cache', false);
                        break;
                    }
                }else{
                    self::updateCache('site_cache',false);
                    $site_cache = self::cache('site_cache', false);
                    break;
                }
            }
        }else{
            self::updateCache('site_cache',false);
            $site_cache = self::cache('site_cache', false);
        }
        if($site == null){//当获取不到site的之后，是微信端的获取，直接从cookie中获取siteid
            $site_id = Fun::getSiteId();
            foreach ($site_cache as $k => $v) {
                if ($site_id == $v['id']) {
                    $site = $v['domain'];
                }
            }
        }
        if ($site == null){
            return false;
        }
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        //return \Yii::createObject($site_cache[$site]['db']);
        \Yii::$app->set('db', $site_cache[$site]['db']);

    }



    /**
     * 获取分店系统的id
     * 2018-03-27对于以后多个微信公众号来说是个坑啊，根本没有考虑多微信公众号的情况的说
     */
    public static function getSiteId()
    {
        $site = null;
        if(method_exists(\Yii::$app->request,'get')){
            $site = \Yii::$app->request->get('site');
        }
        if($site == null){//当获取不到site的之后，是微信端的获取，直接从cookie中获取siteid
            if(\Yii::$app->session->get('site_id')){
                $site_id =  (int)\Yii::$app->session->get('site_id');
                if(!empty($site_id)){
                    return $site_id;
                }else{
                    return null;
                }
            }else{
                if (!empty(\Yii::$app->user->isGuest) && !\Yii::$app->user->isGuest) {//如果已经登录用户了结果site_id还是空，那如果默认的还没有找到，那就需要用户自己到分城市中选择了
                    $customer_id = \Yii::$app->user->id;
                    if(isset(\Yii::$app->params['mode']) && !empty(\Yii::$app->params['mode'])){//综合体、共同体的params.php中设置不同的值 1,2,3
                        $mode = \Yii::$app->params['mode'];
                        $crr = CustomerRegisterRelation::findOne(['customer_id'=>$customer_id,'mode'=>$mode]);//用户注册时的site_id来作为site_id暂放于session中
                        $site_id = $crr->site_id?$crr->site_id:null;
                        if(!empty($site_id)){
                            \Yii::$app->session->set('site_id',$site_id);
                            return (int)$site_id;
                        }else{
                            return null;
                        }
                    }else{
                        return null;
                    }
                }else{
                    /*2017-02-03 start:共同体一个公众号，包含多个城市*/
                    //echo "<script type='text/javascript'>alert('对不起，网页间隔时间过长导致session失效，请重新通过自定义菜单进入');document.onload = window.close();</script>";
                    return null;
                    /*2017-02-03 end:共同体一个公众号，包含多个城市*/
                }
            }
        }
        $site_cache = self::cache('site_cache', false);
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['id'])) return false;
        return $site_cache[$site]['id'];
    }

    /*
     * 获取当前分店所属的模式
     */
    public static function getSiteMode($site_id=null){
        $site_mode = null;
        if($site_id == null){//当获取不到site的之后，是微信端的获取，直接从cookie中获取siteid
            $site_id = Fun::getSiteId();
            if(\Yii::$app->session->get('site_mode')){

                $site_mode =  \Yii::$app->session->get('site_mode');
                return $site_mode;
            }
        }
        $site_cache = Fun::cache('site_cache',false);
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site_mode = $v['mode'];
            }
        }
        return $site_mode;
    }

    /**
     * 获取分店代码
     */
    public static function getSiteBySiteID($site_id)
    {
        $site_cache = self::cache('site_cache', false);
        $site_info = [];
        foreach ($site_cache as $v) {
            if ($v['id'] == $site_id) {
                $site_info = $v;
                break;
            }
        }
        return !empty($site_info) ? $site_info['site_no'] : false;
    }

    /**
     * 获取分店系统的数据库连接信息
     */
    public static function getSiteName()
    {
        $site = \Yii::$app->request->get('site');
        $site_cache = self::cache('site_cache', false);
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        return $site_cache[$site]['name'];
    }

    /**
     * 获取菜单值
     */
    public static function getCurrentMenu($menu, $m = '', $c = '', $a = '', $param = '')
    {
        $module = (\Yii::$app->id == \Yii::$app->controller->module->id)?'':\Yii::$app->controller->module->id;
        $m = !empty($m) ? $m : $module;
        $c = !empty($c) ? $c : \Yii::$app->controller->id;
        $a = !empty($a) ? $a : \Yii::$app->controller->action->id;
        if (empty($param)) {
            $param = self::getDifferenceMenuParam();
        }
        foreach ($menu as $v) {
            if ($v['param'] != null) {
                $v['param'] = Util::param2array($v['param']);
                $key = array_keys($v['param']);
                $parray_array = [];
                foreach (\Yii::$app->params['url_param'] as $kx) {
                    if (in_array($kx, $key)) {
                        $parray_array[$kx] = $v['param'][$kx];
                    }
                }
                $v['param'] = Util::array2param($parray_array);
            }
            //$module = !empty($v['m']) ?: $m;
//            print_r($this->cont);die;
            if ($m == $v['m'] && $c == $v['c'] && $a == $v['a'] && $param == $v['param']) {
                return $v;
            }
        }
    }

    /* 无用且不用wechatsdk了public static function getWechat($site_id)
     {
         if (!isset($site_id)) {
             return false;
         }
         $web_site_id=Site::findOne([$site_id]);
         if ($web_site_id===null) {
             return false;
         }

         \Yii::$app->set('db', \Yii::$app->params['web_db']);
         $wechat=Wechat::findOne(['web_site_id'=>$web_site_id->web_site_id]);
         if (!isset($wechat)) {
             return false;
         }

         \Yii::$app->set('wechat', [
             'class' => '\callmez\wechat\sdk\MpWechat',
             'appId' => isset($wechat['key']) ? $wechat['key'] : '',
             'appSecret' => isset($wechat['secret']) ? $wechat['secret'] : '',
             'token' => isset($wechat['token']) ? $wechat['token'] : '',
             'encodingAesKey' => isset($wechat['encoding_aes_key']) ? $wechat['encoding_aes_key'] : '',
         ]);
         \Yii::$app->set('db', \Yii::$app->params['sys_back_db']);
         return true;
     }*/

    /**
     * 取得当前访问地址中能区分菜单的参数
     */
    public static function getDifferenceMenuParam()
    {
        $param_get = \Yii::$app->request->get();
        if ($param_get == null) return '';
        $key = array_keys($param_get);
        $parray_array = [];

        foreach (\Yii::$app->params['url_param'] as $kx) {
            if (in_array($kx, $key)) {
                $parray_array[$kx] = $param_get[$kx];
            }
        }
        return Util::array2param($parray_array);
    }

    public static function asArray($models, $expand = [])
    {
        $new_array = [];
        foreach ($models as $index => $value) {
            $new_array[$index] = $value->toArray([], $expand);
        }
        return $new_array;
    }

    public static function toTreeArray($models, $expand = [])
    {
        $new_array = [];
        foreach ($models as $index => $value) {
            $value = $value->toArray([], $expand);
            $value['text'] = $value['name'];
            $new_array[$index] = $value;
        }
        return $new_array;
    }

    /**
     * 将菜单数组转成系统url地址
     * @param array $menu
     * @return string
     */
    public static function createMenuUrl($menu, $data = [], $param = [])
    {
        $url = trim($menu['m'] . '/' . $menu['c'] . '/' . $menu['a'], '/');
        $url = '/' . $url;
        if (!empty($menu['param'])) {
            $menuParam = $menu['param'];
            foreach ($data as $k => $v) {
                $menuParam = str_replace('{$' . $k . '}', $v, $menuParam);
            }
            $url = ArrayHelper::merge([$url], Util::param2array($menuParam));
        } else {
            $url = [$url];
        }
        return Fun::url($url);
    }

    public static function getPermissionStr($menu_info)
    {
        $str = !empty($menu_info['m']) ? $menu_info['m'] . '_' . $menu_info['c'] . '_' . $menu_info['a'] : $menu_info['c'] . '_' . $menu_info['a'];
        if (!empty($menu_info['param'])) {
            $param = Util::param2array($menu_info['param']);
            foreach ($param as $k => $v) {
                //var_dump($param);die;
                $str .= in_array($k, \Yii::$app->params['url_param']) ? '_' . $v : '';
            }
        }
        return $str;
    }

    //取得缓存中的字段
    public static function getCacheColumn($array = [], $condition = [], $columns = [])
    {
        $arr = [];
        if ($array != null) {
            foreach ($array as $k => $v) {
                $flag = true;
                if ($condition != null) {
                    foreach ($condition as $key => $val) {
                        if ((is_array($val) && !in_array($v[$key], $val)) || (!is_array($val) && $v[$key] != $val)) {
                            $flag = false;
                        }
                    }
                }
                if ($flag) {
                    if ($columns == null) {
                        $arr[$k] = $v;
                    } else {
                        foreach ($columns as $n) {
                            $arr[$k][$n] = $v[$n];
                        }
                    }
                }
            }
        }
        return $arr;
    }
    //获取业务总监负责的机构id
    public static function getDirectorMechanicIds(){
        $mechanicIds = [];
        $auth = \Yii::$app->authManager;
        $roles = $auth->getRolesByUser(\Yii::$app->user->id);
        $arr = [];
        if(!empty($roles)){
             foreach ($roles as $item){
                 $arr[] = $item->name;
             }
        }
        if(in_array('class_director',$arr)){
            $mechanicIds = (new \yii\db\Query())->from('{{%mechanic}}')->select('id')->where(['admin_id'=>\Yii::$app->user->id])->column(Fun::getSiteDb());
        }
        return $mechanicIds;
    }
    //得到上课时间
    public static function getClassTime($start_time, $end_time, $class_day = 0)
    {
        $time = '';
        $day = '';
        switch ($class_day) {
            case 1:
                $day = '星期一';
                break;
            case 2:
                $day = '星期二';
                break;
            case 3:
                $day = '星期三';
                break;
            case 4:
                $day = '星期四';
                break;
            case 5:
                $day = '星期五';
                break;
            case 6:
                $day = '星期六';
                break;
            case 7:
                $day = '星期天';
                break;
        }
        if ($start_time != null && $end_time != null) {
            $len = strlen($start_time) - 2;
            $lenth = strlen($end_time) - 2;
            $start_time = ($len == 1) ? ('0' . floor($start_time / 100) . ':' . substr($start_time, 1)) : (floor($start_time / 100) . ':' . substr($start_time, 2));
            $end_time = ($lenth == 1) ? ('0' . floor($end_time / 100) . ':' . substr($end_time, 1)) : (floor($end_time / 100) . ':' . substr($end_time, 2));
            $time = (empty($day)) ? ($start_time . '-' . $end_time) : ($day . ' ' . $start_time . '-' . $end_time);
        }
        return $time;
    }

    public static function getClassTimes($start_time, $end_time, $class_day = 0)
    {
        $time = '';
        $day = '';
        switch ($class_day) {
            case 1:
                $day = '星期一';
                break;
            case 2:
                $day = '星期二';
                break;
            case 3:
                $day = '星期三';
                break;
            case 4:
                $day = '星期四';
                break;
            case 5:
                $day = '星期五';
                break;
            case 6:
                $day = '星期六';
                break;
            case 7:
                $day = '星期天';
                break;
        }
        $time = (empty($day)) ? ($start_time . '-' . $end_time) : ($day . ' ' . $start_time . '-' . $end_time);
        return $time;
    }

    public static function getClassDay($class_day = 0)
    {
        $day = '';
        switch ($class_day) {
            case 1:
                $day = '星期一';
                break;
            case 2:
                $day = '星期二';
                break;
            case 3:
                $day = '星期三';
                break;
            case 4:
                $day = '星期四';
                break;
            case 5:
                $day = '星期五';
                break;
            case 6:
                $day = '星期六';
                break;
            case 7:
                $day = '星期天';
                break;
        }
        return $day;
    }

    public static function getDomain()
    {
        //$siteId =(int)\Yii::$app->request->cookies->getValue('site_id');
        $siteId = 2;
        $siteCache = self::cache('site_cache');
        if ($siteId == null) return false;
        foreach ($siteCache as $k => $v) {
            if ($siteId == $v['id']) $siteDomain = $v['domain'];
        }
        if (!isset($siteDomain)) return false;
        return $siteDomain;
    }

    //取得IP地址
    public static function getCity($ip)
    {
        empty($ip) && $ip = \Yii::$app->request->getUserIp();
        if ($ip == "127.0.0.1" || $ip == '::1') return "本机地址";
        $api = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip";
        $json = @file_get_contents($api);//调用新浪IP地址库
        $arr = json_decode($json, true);//解析json
        return $arr;
    }

    /*无用且不要用mpwechat了public static function checkWechatSite($event)
    {
        if (\Yii::$app->controller->module->id == 'app-wechat') {
            $site = \Yii::$app->request->get('site');
            $site_cache = self::cache('website_cache', false);
            $site_id = $site_cache[$site]['id'];
            $wechat_cache = Fun::cache('wechat_cache', false);
            $wechat = isset($wechat_cache[$site_id]) ? $wechat_cache[$site_id] : '';
            if (!isset($site_cache[$site])) $event->isValid = false;
            \Yii::$app->set('wechat', [
                'class' => '\callmez\wechat\sdk\MpWechat',
                'appId' => isset($wechat['key']) ? $wechat['key'] : '',
                'appSecret' => isset($wechat['secret']) ? $wechat['secret'] : '',
                'token' => isset($wechat['token']) ? $wechat['token'] : '',
                'encodingAesKey' => isset($wechat['encoding_aes_key']) ? $wechat['encoding_aes_key'] : '',
            ]);
            \Yii::$app->set('authClientCollection', [
                'class' => 'yii\authclient\Collection',
                'clients' => [
                    'wechat' => [
                        'class' => 'wechat\components\authclient\WechatOAuth',
                        'clientId' => isset($wechat['key']) ? $wechat['key'] : '',
                        'clientSecret' => isset($wechat['secret']) ? $wechat['secret'] : ''
                    ]
                ],
            ]);
        }
    }*/

    /**
     * 获取web菜单值
     */
    public static function getWebCurrentMenu($menu, $m = '', $c = '', $a = '', $param = '')
    {
        $m = !empty($m) ? $m : \Yii::$app->controller->module->uniqueId;
        $c = !empty($c) ? $c : \Yii::$app->controller->id;
        $a = !empty($a) ? $a : \Yii::$app->controller->action->id;
        if (empty($param)) {
            $param = self::getWebDifferenceMenuParam();
        }
        foreach ($menu as $v) {
            $menuParam = self::getWebDifferenceMenuParam($v['param']);
            if (!empty($param) && !empty($menuParam)) {
                $result = array_diff_assoc($param, self::getWebDifferenceMenuParam($v['param']));
                if ($m == $v['m'] && $c == $v['c'] && $a == $v['a'] && empty($result)) {
                    return $v;
                }
            } else {
                if (empty($v['m']) && empty($m)) {
                    if ($c == $v['c'] && $a == $v['a']) {
                        return $v;
                    }
                }
                if ($m == $v['m'] && $c == $v['c'] && $a == $v['a']) {
                    return $v;
                }
            }
        }
    }

    /**
     * 取得当前访问地址中能区分菜单的参数
     */
    public static function getWebDifferenceMenuParam($param = '')
    {
        $param_get = !empty($param) ? Util::param2array($param) : \Yii::$app->request->get();
        if (empty($param_get)) return [];
        $key = array_keys($param_get);
        $parray_array = [];
        foreach (\Yii::$app->params['url_param'] as $kx) {
            if (in_array($kx, $key)) {
                $parray_array[$kx] = $param_get[$kx];
            }
        }
        return $parray_array;
    }


    /**
     *  根据类型获取属性
     *  return string
     */

    public static function getAttribute($type_id = 0,$goods_id = 0)
    {
        $html = '';
        $attr = Attribute::find()->where(['type_id'=>$type_id,'is_show'=>1])->all();
        $goodsattr = GoodsAttr::find()->where(['goods_id'=>$goods_id,'obj_type'=>'attribute'])->asArray()->all(Fun::getSiteDb());
        $farr = [];
        if($goodsattr){
            foreach($goodsattr as $g){
                $farr[$g['attribute_id']] =$g;
            }
        }
        if($attr){
            foreach($attr as $val){
                $html .= '<tr>';
                $html .= '<th  class="zx-goods-table">'.$val->name.'</th>';
                $html .= '<td>';
                $html .= Html::hiddenInput('attribute['.$val->id.']',$val->name);
                if($val->attr_input_type == 'select'){
                    $attr_value = AttributeValue::find()->where(['attr_id'=>$val->id])->all();
                    $html .= Html::dropDownList('attr_value['.$val->id.']', isset($farr[$val->id])?$farr[$val->id]['value']:'', ArrayHelper::map($attr_value, 'value', 'value'),['prompt'=>'请选择','class'=>'form-control']);
                }elseif($val->attr_input_type == 'input'){
                    $html .=  Html::textInput('attr_value['.$val->id.']', isset($farr[$val->id])?$farr[$val->id]['value']:'', ['class' => 'input-text']);
                }else{
                    $html .= Html::textarea('attr_value['.$val->id.']',isset($farr[$val->id])?$farr[$val->id]['value']:'',['class'=>'input-textarea']);
                }
                $html .= '</td>';
                $html .= '</tr>';
            }
        }

        return $html;

    }

    public static function getExtendattributeDetails($type_id=0, $goods_id=0){
        $html = '';
        $attr = Attribute::find()->where(['type_id'=>$type_id])->all();
        $goodsattr = GoodsAttr::find()->where(['goods_id'=>$goods_id])->asArray()->all(Fun::getSiteDb());
        $farr = [];
        if($goodsattr){
            foreach($goodsattr as $g){
                $farr[$g['attribute_id']] = $g;
            }
        }
        if($attr){
            foreach($attr as $val){
                $html .= '<tr>';
                $html .= '<td>'.$val->name.'</td>';
                $html .= '<td>';
                if($val->attr_input_type == 'select'){
                    $attr_value = AttributeValue::find()->where(['attr_id'=>$val->id])->all();
                    $html .= Html::dropDownList('attr_value['.$val->id.']',isset($farr[$val->id])?$farr[$val->id]['value']:'',ArrayHelper::map($attr_value, 'value', 'value'),['prompt'=>'请选择','class'=>'form-control','disabled'=>true]);
                }elseif($val->attr_input_type == 'input'){
                    $html .= isset($farr[$val->id])?$farr[$val->id]['value']:'';
                }else{
                    $html .= isset($farr[$val->id])?$farr[$val->id]['value']:'';
                }
                $html .= '</td>';
                $html .= '</tr>';
            }
        }
        return $html;
    }

    //图片根据配置显示,暂时没用上，后期前端网站显示要用
    public static function getImageshow($url='',$mediaposroute='',$mediaposappname=''){
        //\Yii::error('url:'.$url.';mediaposroute:'.$mediaposroute.';mediaposappname:'.$mediaposappname);
        if(empty($url) || empty($mediaposappname) || empty($mediaposroute)){
            return '';
        }else{
            $mediaposition = MediasPosition::findOne(['posrelated_route'=>$mediaposroute,'appid_name'=>$mediaposappname]);
            $position_id = $mediaposition->id;
            $mediaconfig = MediasConfig::findOne(['mediaposition_id'=>$position_id]);
            $configvar = unserialize($mediaconfig->mediaconfig_var);
            $media_suffix = $configvar['h'].'h_'.$configvar['w'].'w_1e_1c';
            if(isset($configvar['water_text'])){
                $fontsize = floor($configvar['w']/10);
                $media_suffix .= '|watermark=2&text='.base64_encode($configvar['water_text']).'&p='.$configvar['water_pos'].'&t='.$configvar['water_transparency'].'&size='.$fontsize;
            }elseif(isset($configvar['water_img'])){
                $waterimg = $configvar['water_img'];
                $waterimg = base64_encode($waterimg);
                $media_suffix .= '|watermark=1&object='.$waterimg.'&p='.$configvar['water_pos'].'&t='.$configvar['water_transparency'];
            }
            $url = $url.'@'.$media_suffix;
            return $url;
        }
    }

    /*获取当前商品的购买数量，如果是课程那就是已预约人数*/
    public static  function getCurrentNum($goods_id){
        $good = Goods::findOne($goods_id);
        $num = 0;
        if(!empty($good)){
            $num = (new \yii\db\Query())
                ->from('{{%orders_items}} oi')
                ->leftJoin('{{%orders}} o','o.id = oi.orders_id')
                ->where(['o.pay_status'=>[1,4],'oi.status'=>1,'oi.goods_id'=>$goods_id])
                ->count('*',Fun::getSiteDb());
        }
        $num = empty($num)?0:$num;
        return $num;
    }

    //获取商品属性
    public static function getGoodsAttr($goods_id =0){
        $goods_attr = (new \yii\db\Query())->from('{{%goods_attr}}')->where(['goods_id'=>$goods_id])->all(Fun::getSiteDb());
        $data = [];
        if($goods_attr) {
            foreach ($goods_attr as $attr) {
                $data[$attr['obj_type']] = $attr['value'];
            }
        }
        return $data;
    }
    //获取商品属性id
    public static function getGoodsAttrId($goods_id =0){
        $goods_attr = (new \yii\db\Query())->from('{{%goods_attr}}')->where(['goods_id'=>$goods_id])->all(Fun::getSiteDb());
        $data = [];
        if($goods_attr) {
            foreach ($goods_attr as $attr) {
                $data[$attr['obj_type']] = $attr['attribute_id'];
            }
        }
        return $data;
    }

    //获取机构id
    public static function getMechanicIds(){
        $mechanicIds = [];
        $mids = [];
        $auth = \Yii::$app->authManager;
        $roles = $auth->getRolesByUser(\Yii::$app->user->id);
        $arr = [];
        if(!empty($roles)){
            foreach ($roles as $item){
                $arr[] = $item->name;
            }
        }
        if(in_array('mechanic',$arr)){
            $mechanic_id = \Yii::$app->user->identity->mechanic_id;
            $mechanicIds = [$mechanic_id];
            $mechanic = (new \yii\db\Query())->from('{{%mechanic}}')->select('*')->where(['id'=>$mechanic_id])->one(Fun::getSiteDb());
            if(!empty($mechanic) && $mechanic['parent_id'] == 0 ){
                $mids = (new \yii\db\Query())->from('{{%mechanic}}')->select('id')->where(['parent_id'=>$mechanic_id,'status'=>1])->column(Fun::getSiteDb());
            }
            $mechanicIds = array_merge($mechanicIds,$mids);

        }
        return $mechanicIds;
    }


    public static function getLeftMenu($array,$mid=0){
        $arr=[];
        foreach($array as $m){
            if($m['parent_id']==$mid && $m['position']<=2 && $m['display']!=0){
                $a['label']=$m['name'];
                $a['icon']=$m['icon'];
                $a['url']='#';
                $a['items']=Fun::getLeftMenu($array,$m['id']);
                $arr[]=$a;
            }
        }
        return $arr;
    }

    //分店后台获取机构分机构id
    public static function getMechanicIdsforfrontend($mechanicid){
        $mechanicIds = [];
        $mids = [];
        $mechanic_id = $mechanicid;
        $mechanicIds = [$mechanic_id];
        $mechanic = (new \yii\db\Query())->from('{{%mechanic}}')->select('*')->where(['id'=>$mechanic_id])->one(Fun::getSiteDb());
        if(!empty($mechanic) && $mechanic['parent_id'] == 0 ){
            $mids = (new \yii\db\Query())->from('{{%mechanic}}')->select('id')->where(['parent_id'=>$mechanic_id])->column(Fun::getSiteDb());
        }
        $mechanicIds = array_merge($mechanicIds,$mids);


        return $mechanicIds;
    }

    //获取会费
    public static function getCustomerfee(){
        $customerfeeData=Setting::findOne(['key' => 'customerfee','branch_id'=>0]);
        $customerfee_info = !empty($customerfeeData->value) ? unserialize($customerfeeData->value) : null;
        $customerfee = null;
        if(!empty($customerfee_info)){
            $customerfee['customer_fee'] = isset($customerfee_info['customer_fee'])?$customerfee_info['customer_fee']:0;
            $customerfee['description'] = isset($customerfee_info['description'])?$customerfee_info['description']:'';
        }
        return $customerfee;
    }

    //获取城市区
    public static function getArea($site_id=null){
        if($site_id == null){
            $site_id = self::getSiteId();
        }
        $region_list = [];
        $site = Site::findOne($site_id);
        $website = (new \yii\db\Query())->from('{{%website}}')->select('name')->where(['id'=>$site->web_site_id])->one(Fun::getSiteDatabases());
        if($website) {
            $region = Regions::find()->where(['like', 'local_name', $website['name']])->one();
            if($region) {
                $r_list = Regions::find()->select('local_name')->where(['p_region_id' => $region->region_id])->all();
                if($r_list) {
                    $region_list = ArrayHelper::map($r_list, 'local_name', 'local_name');
                }
            }
        }
        return $region_list;
    }

    public static function getWebsiteId_bak($site_id = null){
        if($site_id == null){
            return 21;
        }else{
            $options_new = \Yii::$app->params['options'][$site_id];
            $app_id = $options_new['app_id'];
            $dbweb = \Yii::createObject(\Yii::$app->params['web_db']);
            $wechat = (new Query())->select('*')->from('{{%wechat}}')
                ->where(['key' => $app_id])
                ->one($dbweb);
            $websiteId = $wechat['web_site_id'];
            return $websiteId;
        }
    }

    public static function getWebsiteId($site_id = null) {//参数没啥用，但是之前代码有这个东西，懒得改一堆就改这一个吧
        $options_new = \Yii::$app->params['options'];
        $app_id = $options_new['app_id'];
        $dbweb = \Yii::createObject(\Yii::$app->params['web_db']);
        $wechat = (new Query())->select('*')->from('{{%wechat}}')
            ->where(['key' => $app_id])->one($dbweb);
        $websiteId = $wechat['web_site_id'];
        return $websiteId;
    }


    /**
     * @param $date
     * @return int
     * 某月第一天
     *
     */
    public static function getCurMonthFirstDay($date) {
        return strtotime(date('Y-m-01', strtotime($date)));
    }

    /**
     * @param $date
     * @return int
     * 某月最后一天
     *
     */
    public static function getCurMonthLastDay($date){
        return strtotime(date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month')));
    }

    public static function getZhtWebsiteId($site_id=null){
        $zht_option=\Yii::$app->params['options_zht'];
        $db_web=\Yii::createObject(\Yii::$app->params['web_db']);
        $wechat = (new Query())->select('*')->from('{{%wechat}}')
            ->where(['key' => $zht_option['app_id']])->one($db_web);
        //$websiteId = $wechat['web_site_id'];
        return $wechat['web_site_id'];

    }

    public static function getAdminrole(){
        $role = \Yii::$app->user->identity->role;
        $data = [];
        if(($role = 'teache_teacher' || $role = 'class_teacher' || $role = 'mechanic' ||$role = 'mec_principal') && $role != 'admin'){
            $data['role'] = $role;
            $data['is_mechanic'] = 1;
            $data['mechanic_id'] = \Yii::$app->user->identity->mechanic_id;
            $data['id'] = \Yii::$app->user->identity->id;
            $data['teacher_id'] = \Yii::$app->user->identity->teacher_id;
        }else{
            $data['role'] = $role;
            $data['is_mechanic'] = 0;
            $data['mechanic_id'] = 0;
            $data['id'] = \Yii::$app->user->identity->id;
            $data['teacher_id'] = 0;
        }
        return $data;
    }
    public static function truncateUtf8String($string, $length, $etc = '...'){
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)
        {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
            {
                if ($length < 1.0)
                {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            }
            else
            {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen)
        {
            $result .= $etc;
        }
        return $result;
    }

    public static function toPhpCode($arr, $i = 0)
    {
        $i++;
        $tb_i = $i * 4;
        $tb = ($i - 1) * 4;
        $tb1_str = '';
        $tb2_str = '';
        for ($j = 0; $j < $tb; $j++) {
            $tb1_str .= ' ';
        }
        for ($jj = 0; $jj < $tb_i; $jj++) {
            $tb2_str .= ' ';
        }
        $mystr = '';
        if (is_array($arr) && !empty($arr)) {
            $mystr .= PHP_EOL . $tb1_str . '[' . PHP_EOL;
            $t_arr = [];
            foreach ($arr as $k => $v) {
                $key = '';
                $value = '';
                if (is_string($k)) {
                    $key = "'" . $k . "'";
                } else {
                    $key = $k;
                }
                if (is_array($v) && !empty($v)) {
                    $value = Fun::toPhpCode($v, $i);
                } else if (is_array($v) && empty($v)) {
                    $value = '[]';

                } else {
                    if (is_string($v)) {
                        $value = "'" . $v . "'";
                    } else if (is_bool($v)) {
                        if ($v) {
                            $value = 'true';
                        } else {
                            $value = 'false';
                        }
                    } else {
                        if (is_null($v)) {
                            $v = "''";
                        }
                        $value = $v;
                    }

                }
                $t_arr[] = $tb2_str . $key . "=>" . $value;
            }
            $mystr .= implode(',' . PHP_EOL, $t_arr);
            $mystr .= PHP_EOL . $tb1_str . ']';
        }
        return $mystr;
    }
}